<template>
	<div>
		<StepTabs :tabs="tabsList" v-model="activeIndex"></StepTabs>
		<div class="from-content" v-if="activeIndex == 1">
			<AplidForm ref="formRef" v-bind="formProjectConfig(subsidyType)" v-model="formModel" @submit="onSubmit">
				<template v-slot:subsidyApplyConfigIdForm>
					<remoteSelect
						class="w-100"
						:disabled="!formModel.subsidyType"
						:key="formModel.subsidyType"
						:paramsObj="{ subsidyType: formModel.subsidyType,isAuthFilter:false,organizationId:userInfo.organizationId }"
						api="view_ofsSubsidyProject_page"
						filterKey="subsidyApplyConfigId"
						filterLabel="projectName"
						propName="projectName"
            placeholder="请选择"
						v-model:modelName="formModel.subsidyProjectName"
						v-model="formModel.subsidyApplyConfigId"
            @change="handleGetProjectInfo"
					></remoteSelect>
				</template>
			</AplidForm>
			<div class="footer-btn fc">
				<el-button @click="formRef.onSubmit()" type="primary">下一步</el-button>
			</div>
		</div>

		<template v-if="activeIndex == 2">
			<div class="config-content">
				<policyArchive :list="nowData.policyRel"></policyArchive>
			</div>
			<div class="footer-btn">
				<div class="block">
					<span class="label">申请日期</span>
					<el-date-picker v-model="formModel.belongDate" type="month" value-format="YYYY-MM-DD"
					:disabled-date="disabledDate" placeholder="请选择日期" />
				</div>
				<div class="w-100 fc">
					<el-button @click="handleProd">上一步</el-button>
					<el-button type="primary" @click="handleNext">下一步</el-button>
				</div>
			</div>
		</template>

		<template v-if="activeIndex == 3">
			<!-- <ApplyReport :nowRowData="{...nowData,...formModel}" @refresh-change="onRefreshChange"></ApplyReport> -->
			<ApplyPerson :nowRowData="{...nowData,...formModel}" @backData="backData"></ApplyPerson>
			<div class="footer-btn">
				<div class="w-100 fc">
					<el-button @click="handleProd">上一步</el-button>
					<el-button type="primary" @click="handleSubmitApply">提交申请</el-button>
				</div>
			</div>
		</template>
	</div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import apiMod from '@/apiMod/index'
import remoteSelect from '@/components/AplidCrud/src/AplidRemote/index'
import StepTabs from '@/views/instOperate/components/StepTabs/index.vue'
import policyArchive from '@/views/instOperate/components/policyArchive/index.vue'
import ApplyPerson from './ApplyPerson/index.vue'
import { formProjectConfig } from '../config'
import { getStore } from '@/utils/store'
import { md5 } from '@/utils/encdecrpt'

const props = withDefaults(defineProps<{
  subsidyType?:string
}>(), {
	subsidyType:"6"
})
const emit = defineEmits(['refresh'])
const formModel:any = ref({
	belongDate: '',
  subsidyType:props.subsidyType,
})

const userInfo = getStore('userInfo') || {}
const formRef = ref(null)
const activeIndex = ref(1)

let projectDate = ref({
	projectStartDate:'',
	projectEndDate:''
})

const disabledDate = (date) =>{
	// 时间不能超过当前月也不能超出项目规定范围
	let startDate = new Date(projectDate.value.projectStartDate)
	let endDate = new Date(projectDate.value.projectEndDate) 
	return date.getTime() > new Date() || date.getTime()<startDate || date.getTime()>endDate
}
const tabsList = [
	{ label: '01.选择补贴项目', value: 1, tip: '选择对应的补贴项目' },
	{ label: '02.申请须知', value: 2, tip: '关于申请扶助对象的政策文件' },
	{ label: '03.提交材料', value: 3, tip: '选择申请对象' },
]

const nowData: any = ref({})

const handleNext = () => {
	if (!formModel.value.belongDate) {
		ElMessage.warning('请选择申请日期')
		return
	}
	nowData.value.belongDate = formModel.value.belongDate
	onNext()
//   const getYearMonth = (belongDate)=> {
//     const year = belongDate.replace('年', '-').replace('月', '').split('-')[0]
//     const month = belongDate.replace('年', '-').replace('月', '').split('-')[1]
//     return { year, month }
//   }
//   apiMod.view_subsidy_getData({
//     projectId:formModel.value.subsidyProjectId,
//     creditCode: userInfo.organizationId,
//     ...getYearMonth(formModel.value.belongDate)
//   }).then(res=> {
//     if(res.data ==0) {
//       onNext()
//     }else {
//       ElMessage.warning('该项目已存在申请，请勿重复申请！')
//     }
//   })
}

const onNext = () => {
	if (activeIndex.value < tabsList.length) {
		activeIndex.value += 1
	}
}

const handleGetProjectInfo = (data)=> {
	if(data){
		projectDate.value.projectStartDate = data.projectStartDate
		projectDate.value.projectEndDate = data.projectEndDate
		formModel.value.subsidyProjectId = data.id
	}
  
}
const handleProd = () => {
	if (activeIndex.value > 1 && activeIndex.value <= tabsList.length) {
		activeIndex.value -= 1
	}
}
const onSubmit = (form, done) => {
	// 获取项目配置
	apiMod.view_ofsSubsidyApplyConfig_view(form.subsidyApplyConfigId).then((res) => {
		nowData.value = {
			...(res.data || {}),
		}
		onNext()
	})

	done()
}

const onRefreshChange  = (formId)=> {
  formModel.value.applyNo =formId
}
let finallData = reactive([])
const handleSubmitApply = () => {
	finallData = []
	formModel.value['objList'].forEach(el=>{
		finallData.push(...el.child)
	})
	finallData.forEach(el=>{
		// el = Object.assign(el,formModel.value)
		el.belongDate = formModel.value.belongDate
		el.subsidyApplyConfigId = formModel.value.subsidyApplyConfigId
		el.subsidyProjectId = formModel.value.subsidyProjectId
		el.subsidyProjectName = formModel.value.subsidyProjectName
		el.subsidyType = formModel.value.subsidyType
		el.subsidyTypeLabel = formModel.value.subsidyTypeLabel
		el.creditCode = userInfo.organizationId
		if(!el.applyNo) {
			const str = [userInfo.organizationId, formModel.value?.belongDate?.replace('-', '').substring(0, 6), formModel.value?.subsidyProjectId,el.idCard].filter(Boolean).join('_')
			el.applyNo = md5(str)
		}
	})

	apiMod.view_ofsSubsidyApply_save_elderly_batch(finallData).then((res) => {
		if(res.code==0){
			if(res.data&&res.data.length>0){
				let val = res.data.every(el=>{
					return el.repeatMsg
				})
				if(!val){
					emit('refresh')
				}
				res.data.forEach(el=>{
					ElMessage({
						type:'warning',
						message:`${el.repeatMsg.msg}老人：${el.repeatMsg.oldmanName}-证件号${el.repeatMsg.idCard}`,
						duration:3000,
						showClose:true
					})
				})
			}
		}
    
  })
}
// 选择申请对象时返回的数据
const backData = (data) =>{
	formModel.value['sumTotal'] = data.reduce((sum,b)=>{
      return sum + b.num
    },0)
	formModel.value['objList'] = data
}

watch(()=>formModel.value.subsidyType,()=> {
    formModel.value.subsidyProjectName = undefined
    formModel.value.subsidyApplyConfigId = undefined
},{
  immediate:true
})
</script>

<style scoped lang="scss">
.from-content {
	width: 50%;
	margin: 100px auto;
}
.config-content {
	padding: 12px;
	margin-top: 20px;
	border: 1px solid #dcdcdc;
	border-radius: 10px;
}
.footer-btn {
	margin-top: 32px;
	.block {
		display: flex;
		align-items: center;
		.label {
			margin-right: 12px;
		}
	}
}
</style>
